//
//  UserEditIdentityCardController.m
//  CheekiOS
//
//  Created by mac on 2017/6/19.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "UserEditIdentityCardController.h"

#import "HSLimitText.h"
#import "BXTextField.h"
#import "UserEditCardCell.h"
#import "UserViewController.h"

#define NUMBERSX @"0123456789X"

@interface UserEditIdentityCardController ()<HSLimitTextDelegate,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)HSLimitText *nametextView;
@property (nonatomic, strong)BXTextField *IdCardView;
@property (nonatomic, copy)  NSString *cardStr;
@property (nonatomic, copy) UIImage *cardpositive;
@property (nonatomic, copy) NSString *cardIndex;
@property (nonatomic, copy) UIImage *cardback;

@end

@implementation UserEditIdentityCardController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavgationBarHiddenNo];
    [self selfTitleFontColor];

    self.title = @"实名认证";
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, KScreenWidth, 121)];
    topView.backgroundColor = [UIColor whiteColor];
    
    UILabel *bglinLab = [UILabel new];
    bglinLab.backgroundColor = RGB(246, 246, 246);
    bglinLab.frame =CGRectMake(0, 0, KScreenWidth, 10);
    [topView addSubview:bglinLab];
    
    UILabel *nameLab = [[UILabel alloc] initWithFrame:CGRectMake(15, bglinLab.bottom, 60,  topView.height/2)];
    nameLab.text = @"真实姓名";
    nameLab.font = FontP(15);
    nameLab.textColor = [UIColor blackColor];
    [topView addSubview:nameLab];
    
    
    _nametextView = [[HSLimitText alloc] initWithFrame:CGRectMake(nameLab.right, bglinLab.bottom,KScreenWidth-15-nameLab.width, topView.height/2) type:TextInputTypeTextfield];
    _nametextView.type =TextInputTypeTextfield;
    _nametextView.delegate = self;
    _nametextView.placeholder = @"请输入您的真实姓名";
    _nametextView.isBecomFirstResponder = NO;
    _nametextView.tag = 1;
    
    [topView addSubview:_nametextView];
    
    
    
    
    UILabel *linlab = [UILabel new];
    linlab.frame = CGRectMake(0, _nametextView.bottom, KScreenWidth, 1);
    linlab.backgroundColor = TheLinColor;
    [topView addSubview:linlab];
    
    UILabel *CardLab = [[UILabel alloc] initWithFrame:CGRectMake(15, linlab.bottom, 60, topView.height/2)];
    CardLab.text = @"身份证号";
    CardLab.font = FontP(15);
    CardLab.textColor = [UIColor blackColor];
    [topView addSubview:CardLab];
    
    
    _IdCardView = [[BXTextField alloc] initWithFrame:CGRectMake(CardLab.right+10, linlab.bottom, KScreenWidth-CardLab.width-15, topView.height/2)];
    _IdCardView.delegate = self;
    _IdCardView.font = FontP(15);
    _IdCardView.placeholder = @"请输入您的身份证号";
    _IdCardView.tag = 2;

    
    [topView addSubview:_IdCardView];

    
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight-64) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableHeaderView = topView;
    
    [self.view addSubview:self.tableView];
    

    
    
    
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0 || indexPath.row == 1) {
        UserEditCardCell *cell = [UserEditCardCell cellWithTableView:tableView indexPath:indexPath];
        if (indexPath.row == 0) {
            cell.imageStr = _cardpositive;
        }else{
            cell.imageStr = _cardback;
        }
        return cell;
    }else{
        static NSString *strBtnIdentCell = @"strBtnIdentCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strBtnIdentCell];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strBtnIdentCell];
            UILabel *btn = [UILabel new];
            btn.text = @"提交审核";
            btn.textColor = [UIColor blackColor];
            btn.textAlignment = NSTextAlignmentCenter;
            btn.font = FontP(15);
            btn.frame = CGRectMake(24, 20, KScreenWidth-48, 50);
            btn.backgroundColor = Colorbackground;
            
            [btn.layer setMasksToBounds:YES];
            btn.layer.cornerRadius = 10;

            cell.backgroundColor = RGB(246, 246, 246);
            [cell.contentView addSubview:btn];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==2) {
        return 100;
    }else{
        return 310;

    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        _cardIndex = @"0";
        [self getPhotosAlert];
    }else if (indexPath.row == 1) {
        _cardIndex = @"1";
        [self getPhotosAlert];

    }else{
    
        [self uploadPhoto];
    }
}

- (void)uploadPhoto{
    if(self.cardpositive ==nil||self.cardback==nil){
        [SVProgressHUD showInfoWithStatus:@"身份认证需要两张图片!"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            
        });
        return ;
    }
    __block NSString *strimg=nil;//接收第一张图
    __block NSString *strimg2= nil;//第二章
    if (self.cardStr.length == 0 || self.nametextView.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请正确填写真实姓名和身份证信息"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            
        });
        return;
    }
    
    [HcardHttpmanager upLoadPhotosWithFile:self.cardpositive WithBelong:@"identifyImage" WithToAublum:KToAublumNO WithAlbumId:nil success:^(id sucess) {
        if(sucess){
            strimg = sucess;
            [HcardHttpmanager upLoadPhotosWithFile:self.cardback WithBelong:@"identifyVedio" WithToAublum:KToAublumNO WithAlbumId:nil success:^(id sucess) {
                if(sucess){
                    strimg2 =sucess;
                    NSDictionary *dict = @{
                                           @"uid":[HQHttpManager getUserId],
                                           @"cardImg":[NSString stringWithFormat:@"%@,%@",strimg,strimg2],
                                           @"cardNo":_cardStr,
                                           @"cardName":self.nametextView.text
                                           };
                    [HcardHttpmanager MakePersionalInfoWithParam:dict success:^(id sucess) {
                        [SVProgressHUD showSuccessWithStatus:@"上传成功,正在审核"];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            
                            
                            for (UIViewController *temp in self.navigationController.viewControllers) {
                                if ([temp isKindOfClass:[UserViewController class]]) {

                                    [self.navigationController popToViewController:temp animated:YES];
                                    [SVProgressHUD dismiss];

                                    return;
                                }
                            }

                        });
                        
                    } failure:^(NSError *error) {
                        
                    }];
                }else{
                    [SVProgressHUD showErrorWithStatus:@"上传失败"];
                }
            } failure:^(NSError *error) {
                [SVProgressHUD showErrorWithStatus:@"上传失败"];
            }];
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"上传失败"];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"上传失败"];
    }];
    
}

#pragma mark - getPhotosAlert
-(void)getPhotosAlert{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *picekerVc = [[UIImagePickerController alloc] init];
        picekerVc.sourceType = UIImagePickerControllerSourceTypeCamera;
        picekerVc.delegate = self;
        [self presentViewController:picekerVc animated:YES completion:nil];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *picekerVc = [[UIImagePickerController alloc] init];
        picekerVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picekerVc.delegate = self;
        [self presentViewController:picekerVc animated:YES completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [self presentViewController:alert animated:YES completion:^{
    }];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = info[UIImagePickerControllerOriginalImage];

    if ([_cardIndex isEqualToString:@"0"]) {
        _cardpositive = image;
    }else{
        _cardback = image;
    }
    NSLog(@"获取的图片为：%@",image);
    [self dismissViewControllerAnimated:YES completion:nil];
    
    [_tableView reloadData];

    
}



#pragma mark============= textFiled Delegate     ===========
- (void)limitTextLimitInput:(HSLimitText *)textLimitInput text:(NSString *)text
{
    if([textLimitInput isEqual:self.nametextView]){
        self.nametextView.text = text;
    }
    
}

- (void)limitTextLimitInputOverStop:(HSLimitText *)textLimitInput
{
    NSLog(@"%@",@"超出什么都不做 直接截断");
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField.tag ==2 ){
        NSCharacterSet*cs;
        cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERSX]invertedSet];
        NSString*filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        BOOL basicTest = [string isEqualToString:filtered];
        if(!basicTest) {
            
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"请正确输入身份证号"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
            return NO;
        }else{
    NSString *text = [textField text];
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789X"];
    string = [string stringByReplacingOccurrencesOfString:@"" withString:@""];
    if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
        return NO;
    }
    text = [text stringByReplacingCharactersInRange:range withString:string];
    text = [text stringByReplacingOccurrencesOfString:@"" withString:@""];
    
    NSString *newString = @"";
    while (text.length > 0) {
        NSString *subString = [text substringToIndex:MIN(text.length, 4)];
        newString = [newString stringByAppendingString:subString];
        if (subString.length == 4) {
            newString = [newString stringByAppendingString:@""];
        }
        text = [text substringFromIndex:MIN(text.length, 4)];
    }
    newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
    // 限制长度
    if (newString.length >= 19) {
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"请正确输入身份证号" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
                }];
                [alertVC addAction:cancelAction];
        
                [self.navigationController presentViewController:alertVC animated:YES completion:nil];
        
        return NO;
    }
    [textField setText:newString];
    _cardStr =textField.text;//证件
    return NO;

        }
    }
        return YES;
}


@end
